package com.example.myapplication.socket;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ChatService {
    private BlockingQueue<String> sendQueue;
    private BlockingQueue<String> receiveQueue;
    private UdpClient udpClient;
    private TcpClient tcpClient;
    private boolean isRunning;

    public ChatService() {
        sendQueue = new LinkedBlockingQueue<>();
        receiveQueue = new LinkedBlockingQueue<>();
        udpClient = UdpClient.getInstance();
        tcpClient = TcpClient.getInstance();
        isRunning = true;

        // Start sender thread
        new Thread(() -> {
            while (isRunning) {
                try {
                    String message = sendQueue.take();
                    if (message != null) {
                        udpClient.sendMessage(message);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
        }).start();

        // Start receiver thread
        new Thread(() -> {
            while (isRunning) {
                try {
                    String message = udpClient.receiveMessage();
                    if (message != null) {
                        receiveQueue.put(message);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void sendMessage(String message) {
        try {
            sendQueue.put(message);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }

    public String receiveMessage() {
        try {
            return receiveQueue.take();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
            return null;
        }
    }

    public void stop() {
        isRunning = false;
        // Optionally, you can add code here to close the clients
    }
}